package com.example.demo.controller;

import com.example.demo.common.JwtUtils;
//import com.example.demo.common.QiniuUtils;
import com.example.demo.common.ResultModel;
import com.example.demo.common.ResultModelTool;
import com.example.demo.common.StringUtil;
import com.example.demo.entity.Picture;
import com.example.demo.entity.User;
import com.example.demo.service.PictureService;
//import com.example.demo.service.UploadImageService;
import com.example.demo.service.UserService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.validation.constraints.Positive;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@Slf4j
@Controller
@RequestMapping("/pictures")
@Transactional
public class PictureController {

   // static String fileLocation = "/restaurantRes/";//图片资源访问路径
    static String fileLocation = "/static/restaurantRes/";//图片资源访问路径
    //存储预返回页面的结果对象
    private Map<String, Object> result = new HashMap<>();
    //注入业务对象
    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private JwtUtils jwtUtils;
/*
* 图片新增
* */
@PostMapping("")
    @ResponseBody
    public ResultModel uploadFood(String description, Part pictureFile,
                                          HttpServletRequest request) {

    String token = request.getHeader("Authorization");
    Claims claims = JwtUtils.parseJwt(token);
    String userId = claims.getId();
    User user1=userService.getUser(userId);
    if(user1==null){
        return new ResultModel(200,"token过期或者权限不足");
    }


        Map<String, Object> result= new HashMap<String,Object>();
        //获取提交文件名称
        String filename = pictureFile.getSubmittedFileName();
    String newfilename=System.currentTimeMillis()+ UUID.randomUUID().toString().replace(".","").substring(0,6)+"."+filename.substring(filename.lastIndexOf(".")+1);

    //定义上传文件存放的路径
        String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
        System.out.println(path);
        //返回保存的url，根据url可以进行文件查看或者下载
        String filePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() //端口 https443端口无需添加
                + fileLocation + newfilename;

        String pictureFileURL = filePath;//根路径+文件名

//插入这条Food数据
        pictureService.insertFood(new Picture(description,pictureFileURL));

        //写入文件
        try {
            pictureFile.write(newfilename);
            result.put("Result", "添加图片信息成功");
        } catch (IOException e) {
            e.printStackTrace();
            result.put("Result", "添加图片信息失败");
        }
       ResultModel resultmodel=new ResultModel();
        resultmodel.setCode(200);
        resultmodel.setData(result);
        return ResultModelTool.handleResultModel(resultmodel);
    }




    /*
     * 图片列表
     * */

        @GetMapping("")
        @ResponseBody
    public ResultModel selectAll() {
        List<Picture> list = pictureService.list();
        ResultModel resultModel = new ResultModel();
        resultModel.setCode(200);
        resultModel.setData(list);
        return ResultModelTool.handleResultModel(resultModel);

    }


    /*
     * 图片删除（删除路径同时删除文件）
     * */
      @DeleteMapping("/{id}")
    @ResponseBody
    public ResultModel  deleteFile(@PathVariable(value = "id") @Positive(message = "{id}") int id) throws IOException {

      String token = request.getHeader("Authorization");
      Claims claims = JwtUtils.parseJwt(token);
      String userId = claims.getId();
      User user1=userService.getUser(userId);
      if(user1==null){
          return new ResultModel(200,"token过期或者权限不足");
      }

    ResultModel resultModel = new ResultModel();
    try {
    String deletePath= pictureService.selectid(id).getPictureFileURL();
    String cc= deletePath.substring(deletePath.lastIndexOf("/")+1);
    //String truepath="d:/restaurantRes/"+cc;
        String truepath="/static/restaurantRes/"+cc;
    System.out.println(deletePath);
    System.out.println(cc);
    File file=new File(truepath);
    file.delete();
        pictureService.delete(id);
        resultModel.setData("删除成功");
        resultModel.setCode(200);
        return ResultModelTool.handleResultModel(resultModel);
    }
    catch(Exception e){
    e.printStackTrace();
    }
      resultModel.setCode(203);//删除失败
      return ResultModelTool.handleResultModel(resultModel);
    }



}